"use client";
import { GameItem, Rank, RankDetail, RankReward } from "@/api/activity";
import Vip from "@/components/Vip";
import clsx from "clsx";
import React from "react";
import styles from "./page.module.scss";

interface Props {
    data: RankDetail;
    rankList: Rank[];
    gamesInfo?: {
        count: number;
        list: GameItem[];
    };
}

const MiddleContainer: React.FC<Props> = ({ data, rankList = [], gamesInfo }) => {
    const headerData = React.useMemo(() => {
        if (!rankList?.length) return [];

        const res = rankList.slice(0, 3);
        const result: any[] = [null, null, null];
        result[0] = res[1];
        result[1] = res[0];
        result[2] = res[2];
        console.log(result);
        return result;
    }, [rankList]);

    const [actId, setActId] = React.useState("middleContainer");
    const actIdRef = React.useRef<string>("middleContainer");

    React.useEffect(() => {
        watchPosition();
    }, []);

    const watchPosition = () => {
        let targetId = "middleContainer";
        hrefCfg.forEach((item) => {
            const dom = document.querySelector(`#${item.id}`);
            if (dom) {
                const rect = dom.getBoundingClientRect();
                if (rect.top < item.spaceTop) {
                    targetId = item.id;
                }
            }
            const stickyBox: any = document.querySelector("#stickyBox");
            if (stickyBox) {
                const stickyRect = stickyBox.getBoundingClientRect();
                if (stickyRect.top < 60) {
                    stickyBox.style.background = "rgba(0,0,0,.7)";
                } else {
                    stickyBox.style.background = "rgba(255,255,255,0)";
                }
            }
        });
        if (actIdRef.current !== targetId) {
        }
        setActId(targetId);
        requestAnimationFrame(watchPosition);
    };
    React.useEffect(() => {
        actIdRef.current = actId;
    }, [actId]);

    const moreList = React.useMemo(() => {
        if (!rankList?.length) return [];
        const res = rankList.slice(3, rankList?.length);
        return res;
    }, [rankList]);

    const showSelfInBottom = React.useMemo(() => {
        return true;
        // return rankList.findIndex((item) => item.rank === data.self_rank.rank) === -1;
    }, [rankList, data]);

    const hrefCfg = React.useMemo(() => {
        return [
            {
                text: "Classificaçães",
                id: "middleContainer",
                spaceTop: 60,
            },
            {
                text: `Jogos(${gamesInfo?.count})`,
                id: "jackpot",
                spaceTop: 100,
            },
            {
                text: "Regras",
                id: "rankFooter",
                spaceTop: 60,
            },
        ];
    }, [gamesInfo]);

    const scrollInto = (item: any) => {
        const dom = document.querySelector(`#${item.id}`);
        // setActId(item.id);
        dom?.scrollIntoView({
            behavior: "smooth",
            block: "start",
        });
    };

    return (
        <>
            <div className={clsx(styles.gideBox, "py-[.1rem]")} id="stickyBox">
                {hrefCfg.map((item) => {
                    return (
                        <div
                            className={clsx(styles.gideItem, {
                                [styles.active]: actId === item.id,
                            })}
                            onClick={() => {
                                scrollInto(item);
                            }}
                            key={item.id}
                        >
                            {item.text}
                        </div>
                    );
                })}
            </div>
            {!!headerData?.length && (
                <div className={styles.middleContainer}>
                    <div className="relative px-[.15rem] pt-[.6rem]">
                        <img src="/rank/bg2.webp" alt="" />
                        <div className={clsx(styles.persons, "px-[.2rem]")}>
                            {headerData.map((item: Rank, idx) => {
                                // const curVip = vipImagesMap.get(item?.vipLevel || 1);
                                // console.log(123123, item);
                                if (!item) {
                                    return <div key={idx} className={styles.personItem}></div>;
                                }
                                return (
                                    <div key={idx} className={styles.personItem}>
                                        {item && (
                                            <>
                                                <img
                                                    src={`/rank/${item.rank}.webp`}
                                                    className={styles.rankImage}
                                                    alt=""
                                                />
                                                <img
                                                    src="https://img1.baidu.com/it/u=1699323843,2372946297&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=983"
                                                    alt=""
                                                    className={styles.userHeader}
                                                />
                                                <Vip
                                                    style={{
                                                        position: "absolute",
                                                        bottom: "-0.25rem",
                                                    }}
                                                    level={item?.vipLevel}
                                                    vipIconClassName="relative z-[3]"
                                                    vipIconStyle={{ width: ".3rem" }}
                                                ></Vip>
                                            </>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                        <div className={clsx(styles.infoBox, "px-[.2rem]")}>
                            {headerData.map((item: Rank, idx) => {
                                let curReward: RankReward = {} as RankReward;
                                if (item?.reward?.length) {
                                    curReward = item?.reward[0];
                                }

                                return (
                                    <div className={styles.infoItem} key={idx}>
                                        {item && (
                                            <>
                                                <div className={styles.userName}>
                                                    {item.nickName}
                                                </div>
                                                <div
                                                    className={clsx(
                                                        styles.usedPoint,
                                                        styles.border
                                                    )}
                                                >
                                                    {item.score}
                                                </div>
                                                <div className={styles.moneyText}>
                                                    R${curReward?.amount || 0}
                                                </div>
                                                <div className={styles.percentBox}>
                                                    {curReward?.ratio || 0}%
                                                </div>
                                            </>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            )}
            {!!moreList?.length && (
                <div className="mt-[.1rem] px-[.1rem]">
                    {moreList.map((item, idx) => {
                        let curReward: RankReward = {} as RankReward;
                        if (item?.reward?.length) {
                            curReward = item?.reward[0];
                        }
                        return (
                            <div
                                className={clsx(styles.normalItem, {
                                    [styles.normarSelf]: item.rank === data.self_rank.rank,
                                })}
                                key={item.rank}
                            >
                                <div className="mr-[.1rem] w-[.6rem] text-center text-[.2rem] font-bold text-[#11de68]">
                                    {item.rank}
                                    {/* {idx + 4} */}
                                </div>
                                <div className={clsx(styles.normalHeader, "mr-[.2rem]")}>
                                    <img
                                        src="https://img1.baidu.com/it/u=1699323843,2372946297&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=983"
                                        alt=""
                                        className={styles.headerImage}
                                    />
                                    <Vip
                                        style={{
                                            position: "absolute",
                                            bottom: "-0.1rem",
                                        }}
                                        level={item.vipLevel}
                                        vipIconClassName="relative z-[3]"
                                        vipIconStyle={{ width: ".3rem" }}
                                    ></Vip>
                                </div>
                                <div className="flex-1">
                                    <div className="text-[.12rem]">{item?.nickName}</div>
                                    <div className={styles.usedPoint}>{item.score}</div>
                                </div>
                                <div className="flex flex-col items-end">
                                    <div className={styles.moneyText}>
                                        R${curReward?.amount || 0}
                                    </div>
                                    <div className={styles.percentBox}>{curReward?.ratio}%</div>
                                </div>
                            </div>
                        );
                    })}
                    {showSelfInBottom && (
                        <div className={clsx(styles.normalItem, styles.normarSelf)}>
                            <div className="mr-[.1rem] w-[.6rem] text-center text-[.2rem] font-bold text-[#11de68]">
                                {data?.self_rank?.rank === -1 ? "-" : data?.self_rank?.rank}
                            </div>
                            <div className={clsx(styles.normalHeader, "mr-[.2rem]")}>
                                <img
                                    src="https://img1.baidu.com/it/u=1699323843,2372946297&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=983"
                                    alt=""
                                    className={styles.headerImage}
                                />
                                <Vip
                                    style={{
                                        position: "absolute",
                                        bottom: "-0.1rem",
                                    }}
                                    level={data?.self_rank?.vipLevel}
                                    vipIconClassName="relative z-[3]"
                                    vipIconStyle={{ width: ".3rem" }}
                                ></Vip>
                            </div>
                            <div className="flex-1">
                                <div className="text-[.12rem]">{data.self_rank.nickName}</div>
                                <div className={styles.usedPoint}>{data.self_rank.score}</div>
                            </div>
                            <div className="flex flex-col items-end">
                                <div className={styles.moneyText}>
                                    R$
                                    {data.self_rank.reward && data.self_rank.reward[0]
                                        ? data.self_rank.reward[0].amount
                                        : 0}
                                </div>
                                <div className={styles.percentBox}>
                                    {data.self_rank.reward && data.self_rank.reward[0]
                                        ? data.self_rank.reward[0].ratio
                                        : 0}
                                    %
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            )}
        </>
    );
};

export default MiddleContainer;
